import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

class SpUtils {
  SharedPreferences? prefs;

  SpUtils._() {
    init();
  }

  static SpUtils? _instance;

  static preInit() {
    _instance ??= SpUtils._();
  }

  static SpUtils getInstance() {

    _instance ??= SpUtils._();

    return _instance!;
  }

  void init() async {
    prefs ??= await SharedPreferences.getInstance();
  }

  saveValue(String key, var value) {
    if (value is String) {
      prefs?.setString(key, value);
    } else if (value is double) {
      prefs?.setDouble(key, value);
    } else if (value is int) {
      prefs?.setInt(key, value);
    } else if (value is bool) {
      prefs?.setBool(key, value);
    } else if (value is List<String>) {
      prefs?.setStringList(key, value);
    } else {
      //存储对象 对象转json存储
      prefs?.setString(key, jsonEncode(value));
    }
  }

  T getValue<T>(String key, {var defValue}) {
    var t = prefs?.get(key) as T;
    return t != null ? t : defValue;
  }

  getObjValue<T>(String key, T Function(dynamic v) param) {
    var json = prefs?.get(key) as String;
    return param(jsonDecode(json));
  }

  remove(String key) {
    prefs?.remove(key);
  }

  clearAll() {
    prefs!.clear();
  }
}
